package site.syksy.qingzhou.security.authentication;

import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import site.syksy.qingzhou.security.domain.GeneralLoginVO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Raspberry
 */
public class GeneralAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String HTTP_METHOD = "POST";

    private boolean postOnly = true;

    private HttpMessageConverter httpMessageConverter;

    public GeneralAuthenticationFilter(String loginUrl,HttpMessageConverter httpMessageConverter) {
        super(new AntPathRequestMatcher(loginUrl, HTTP_METHOD));
        this.httpMessageConverter = httpMessageConverter;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        if (postOnly && !request.getMethod().equals(HTTP_METHOD)) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(request);
        MediaType contentType = servletServerHttpRequest.getHeaders().getContentType();
        if (!contentType.includes(MediaType.APPLICATION_JSON)) {
            throw new AuthenticationServiceException(
                    "Authentication content type not supported: " + request.getContentType());
        }
        GeneralLoginVO generalLoginVO = (GeneralLoginVO) httpMessageConverter.read(GeneralLoginVO.class, servletServerHttpRequest);
        GeneralAuthenticationToken authRequest = new GeneralAuthenticationToken(generalLoginVO);
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
